package com.zhang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhang.mapper.ArticleMapper;
import com.zhang.pojo.Article;
import com.zhang.pojo.Category;
import com.zhang.pojo.PageBean;
import com.zhang.service.ArticleService;
import com.zhang.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @program: big_event
 * @description: TODO
 * @author: Mr.Zhang
 * @create: 2024-04-06 13:45
 **/
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 新增文章  该接口用于新增文章(发布文章)
     * @param article
     */
    @Override
    public void add(Article article) {
        // 补充属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        article.setCreateUser(userId);

        articleMapper.add(article);
    }

    /**
     * 条件分页列表查询
     * 该接口用于根据条件查询文章,带分页
     * @param pageNum
     * @param pageSize
     * @param categoryId
     * @param state
     * @return
     */
    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //1、创建PageBean对象
        PageBean<Article> pd = new PageBean<>();

        //2、开启分页查询  Maven引用pageHelper
        PageHelper.startPage(pageNum, pageSize);

        //3、调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as = articleMapper.list(userId,categoryId,state);
        //page中提供了方法，可以获取pageHelper分页查询，得到的总记录条数和当前页数据
        Page<Article> p = (Page<Article>) as;

        //把数据填充到PageBean中
        pd.setTotal(p.getTotal());
        pd.setItems(p.getResult());
        return pd;
    }

    /**
     * 根据ID获取文章详细信息
     * @param id
     * @return
     */
    @Override
    public Article detail(Integer id) {
        Article article = articleMapper.detail(id);
        return article;
    }


    /**
     * 更新文章信息
     * @param article
     */
    @Override
    public void update(Article article) {
        //更新时间
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);

    }

    /**
     * 根据ID删除文章
     * @param id
     */
    @Override
    public void delete(Integer id) {
       articleMapper.delete(id);
    }
}
